import { onBeforeUnmount } from 'vue'

interface RemLayoutOptions {
  /** 设计稿宽度  */
  designWidth?: number
  /** 基准值 1rem = N
   * @default 100
   */
  base?: number
  /** reCalc 计算时间  */
  event?: keyof WindowEventMap
  /** hook 是否开启内部生命周期 */
  cycle?: boolean
}

export function useRemLayout(options?: RemLayoutOptions) {
  const { designWidth = 1920, base = 100, event = 'resize' } = options || {}

  const docEl = document.documentElement as any

  const originSize = docEl!.fontSize

  observerSize()

  onBeforeUnmount(() => {
    stopObserverSize()
  })

  function resize() {
    let _clientWidth = docEl.clientWidth

    if (!_clientWidth) return
    // 只针对 1920PX, 大于1920都以1920计算
    if (_clientWidth > designWidth) {
      _clientWidth = designWidth
    }

    const scale = _clientWidth / designWidth
    docEl.style.fontSize = base * scale + 'px'
  }

  function stopObserverSize() {
    if (!originSize) {
      document.getElementsByTagName('html')[0].style.fontSize = ''
    } else {
      document.documentElement.style.fontSize = originSize + 'px'
    }

    window?.removeEventListener(event, resize)
  }

  function observerSize(handler = () => {}) {
    resize()
    window?.addEventListener(event, resize, false)
    if (typeof handler === 'function') {
      handler()
    }

    return stopObserverSize
  }

  return { observerSize, stopObserverSize }
}
